package com.gc.materialdesign.widgets;

import com.gc.materialdesign.ResourceTable;
import com.gc.materialdesign.utils.ShapeUtil;
import com.gc.materialdesign.utils.Utils;
import com.gc.materialdesign.views.ButtonFlat;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.multimodalinput.event.KeyEvent;

public class SnackBar extends CommonDialog {
    private static final int TASK_CODE = 502;

    private String text;
    private int textSize = 14; // Roboto Regular 14fp
    private String buttonText;
    private Component.ClickedListener onClickListener;
    private Context context;
    private Component view;
    private ButtonFlat button;
    private String backgroundSnackBar = "#333333";
    private String backgroundButton = "#1E88E5";

    private OnHideListener onHideListener;
    // Timer
    private boolean mIndeterminate = false;
    private int mTimer = 3 * 1000;

    // Only text
    public SnackBar(Context context, String text) {
        super(context);
        this.context = context;
        this.text = text;
    }

    // With action button
    public SnackBar(Context context, String text, String buttonText, Component.ClickedListener onClickListener) {
        super(context);
        //        setTransparent(true);
        getWindow().addWindowFlags(WindowManager.LayoutConfig.MARK_DIM_EVE_WINDOW_BEHIND);
        this.context = context;
        this.text = text;
        this.buttonText = buttonText;
        this.onClickListener = onClickListener;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        setAutoClosable(false);
        setTransparent(true);
        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_snackbar, null, false);
        setContentCustomComponent(component);
        Text tv = (Text) component.findComponentById(ResourceTable.Id_text);
        tv.setText(text);
        tv.setTextSize(textSize, Text.TextSizeType.FP);
        button = (ButtonFlat) component.findComponentById(ResourceTable.Id_buttonflat);
        if (text == null || onClickListener == null) {
            button.setVisibility(Component.HIDE);
        } else {
            button.setText(buttonText);
            button.getTextView().setTextSize(textSize, Text.TextSizeType.FP);
            button.setBackgroundColor(backgroundButton);

            button.setClickedListener(
                    view -> {
                        hide();
                        onClickListener.onClick(view);
                    });
        }
        view = component.findComponentById(ResourceTable.Id_snackbar);
        view.setBackground(ShapeUtil.createDrawable(Color.getIntColor(Utils.rgba(backgroundSnackBar))));
    }

    @Override
    public void dealBackKeyDown() {}

    @Override
    public void show() {
        super.show();
        view.setVisibility(Component.VISIBLE);
        new AnimatorProperty(view).moveFromY(view.getHeight()).moveToY(0).setDuration(300).start();
        if (!mIndeterminate) {
            dismissTimer.start();
        }
    }

    // Dismiss timer
    private Thread dismissTimer =
            new Thread(
                    () -> {
                        try {
                            Thread.sleep(mTimer);
                        } catch (InterruptedException e) {
                            e.toString();
                        }

                        MyEventHandler myEventHandler = new MyEventHandler(EventRunner.create());
                        InnerEvent innerEvent = InnerEvent.get();
                        innerEvent.eventId = TASK_CODE;
                        myEventHandler.sendEvent(innerEvent);
                    });

    private class MyEventHandler extends EventHandler {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }

        @Override
        public void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            int eventId = event.eventId;
            switch (eventId) {
                case TASK_CODE:
                    context.getUITaskDispatcher()
                            .asyncDispatch(
                                    () -> {
                                        if (onHideListener != null) {
                                            onHideListener.onHide();
                                        }
                                        hide();
                                    });
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 隐藏回调
     * @author Jack Tony
     */
    @Override
    protected void onHide() {
        super.onHide();
        AnimatorProperty animatorProperty = new AnimatorProperty(view);
        animatorProperty.moveFromY(0).moveToY(view.getHeight()).setDuration(300);
        animatorProperty.setStateChangedListener(
                new Animator.StateChangedListener() {
                    @Override
                    public void onStart(Animator animator) {}

                    @Override
                    public void onStop(Animator animator) {}

                    @Override
                    public void onCancel(Animator animator) {}

                    @Override
                    public void onEnd(Animator animator) {
                        SnackBar.super.hide();
                    }

                    @Override
                    public void onPause(Animator animator) {}

                    @Override
                    public void onResume(Animator animator) {}
                });
        animatorProperty.start();
    }

    @Override
    public boolean clickKeyDown(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEY_BACK) {
            hide();
        }
        return super.clickKeyDown(event);
    }

    public void setMessageTextSize(int size) {
        textSize = size;
    }

    public void setIndeterminate(boolean indeterminate) {
        mIndeterminate = indeterminate;
    }

    public boolean isIndeterminate() {
        return mIndeterminate;
    }

    public void setDismissTimer(int time) {
        mTimer = time;
    }

    public int getDismissTimer() {
        return mTimer;
    }

    /**
     * Change background color of SnackBar
     *
     * @param color
     */
    public void setBackgroundSnackBar(String color) {
        backgroundSnackBar = color;
        if (view != null) {
            view.setBackground(ShapeUtil.createDrawable(Color.getIntColor(Utils.rgba(color))));
        }
    }

    /**
     * Chage color of FlatButton in Snackbar
     *
     * @param color
     */
    public void setColorButton(String color) {
        backgroundButton = color;
        if (button != null) {
            button.setBackground(ShapeUtil.createDrawable(Color.getIntColor(Utils.rgba(color))));
        }
    }

    /**
     * This event start when snackbar dismish without push the button
     *
     * @author Navas
     */
    public interface OnHideListener {
        void onHide();
    }

    public void setOnHideListener(OnHideListener onHideListener) {
        this.onHideListener = onHideListener;
    }
}
